﻿using Blm.Utils.Extensions;
using Language.Resource;
using Microsoft.Extensions.Localization;
using System;
using System.Threading.Tasks;
using VisionCloud.Core.Model.Sys;
using VisionCloud.Domain.Common;
using VisionCloud.Domain.DtoModel.Sys;
using VisionCloud.Domain.Repository.Interface.Sys;
using VisionCloud.Domain.UnitOfWork;

namespace VisionCloud.Service.Sys
{
    public class MenuFuncService
    {
        public IUnitOfWork UnitOfWork { get; set; }

        public ISysMenuFuncRepository SysMenuFuncRepository { get; set; }
        public IStringLocalizer<ServiceResource> Localizer { get; set; }

        #region 菜单功能

        public async Task<bool> Existed(SysMenuFuncDto model)
        {
            return await SysMenuFuncRepository.AnyAsync(p => p.Name.ToLower() == model.Name.ToLower());
        }

        public async Task<ApiPageResult> GetMenuFuncPage(SysMenuFuncCondition conditon)
        {
            return await SysMenuFuncRepository.GetPage(conditon);
        }

        public async Task CreateMenuFunc(SysMenuFuncDto model, Guid opeId)
        {
            var exists = await Existed(model);
            if (exists == true)
            {
                throw new OperationException(Localizer["YB0220"].Value);
            }

            var entity = model.CopyTo<SysMenuFunc>();
            entity.MenuFuncId = Guid.NewGuid();
            entity.CreatedBy = opeId;
            entity.CreatedDate = DateTime.Now;
            entity.LastUpdatedBy = opeId;
            entity.LastUpdatedDate = DateTime.Now;

            SysMenuFuncRepository.Add(entity);

            await UnitOfWork.SaveChangesAsync();
        }

        public async Task DeleteMenuFunc(Guid MenuFuncId, Guid opeId)
        {
            SysMenuFuncRepository.Update(t => t.MenuFuncId == MenuFuncId, d =>
            {
                d.IsDeleted = true;
                d.MenuFuncId = MenuFuncId;
                d.LastUpdatedBy = opeId;
                d.LastUpdatedDate = DateTime.Now;
            });

            await UnitOfWork.SaveChangesAsync();
        }

        public async Task UpdateMenuFunc(SysMenuFuncDto model, Guid opeId)
        {
            var entity = model.CopyTo<SysMenuFunc>();
            entity.LastUpdatedBy = opeId;
            entity.LastUpdatedDate = DateTime.Now;
            SysMenuFuncRepository.Update(entity);

            await UnitOfWork.SaveChangesAsync();
        }

        public async Task<SysMenuFuncDto> FindMenuFunc(SysMenuFuncDto SysMenuFuncDto)
        {
            return await SysMenuFuncRepository.FindSysMenuFunc(SysMenuFuncDto);
        }

        #endregion 菜单功能
    }
}